﻿using MemberManagement.Attributes;
using MemberManagement.Common;
using MemberManagement.Entity;
using MemberManagement.Extensions;
using MySql.Data.EntityFramework;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MemberManagement.Context
{
    [DbConfigurationType(typeof(MySqlEFConfiguration))]
    public class MyContext : DbContext
    {

        public MyContext() : base("name=DefaultConnString")
        {
            Database.SetInitializer(new SeedDataInitializer());
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //移除EF映射默认给表名添加“s“或者“es”
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            //添加精度控制
            modelBuilder.Conventions.Add(new DecimalPrecisionAttributeConvention());
            base.OnModelCreating(modelBuilder);
        }

        /// <summary>
        /// 模型验证出错时抛出异常
        /// </summary>
        /// <returns></returns>
        public override int SaveChanges()
        {
            try
            {
                return base.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                var errMsg = ex.EntityValidationErrors.SelectMany(o => o.ValidationErrors).Select(o => o.ErrorMessage);
                var fullErrMsg = ex.Message + ":" + string.Join(";", errMsg);
                throw new DbEntityValidationException(fullErrMsg, ex.EntityValidationErrors);
            }
        }

        public DbSet<Member> Member { get; set; }
        public DbSet<SysConfig> SysConfig { get; set; }
        public DbSet<Recharge> Recharge { get; set; }

        internal class SeedDataInitializer : CreateDatabaseIfNotExists<MyContext>
        {
            protected override void Seed(MyContext context)
            {
                base.Seed(context);
                context.Set<SysConfig>().AddRange(new SysConfig[] 
                {
                    new SysConfig()
                    {
                        Key = ConstKey.PwdKey,
                        Value = "123456".DESEncrypt()
                    },
                    new SysConfig()
                    {
                        Key = ConstKey.AmountKey,
                        Value = "25"
                    }
                });
            }
        }
    }

    public static class DbContextExtensions
    {
        /// <summary>
        /// 更新一条记录(会查询数据库)
        /// </summary>
        /// <param name="entity">要修改的记录</param>
        /// <returns></returns>
        public static T Update<T>(this DbContext context, T entity) where T : class, new()
        {
            DbEntityEntry<T> entry = context.Entry(entity);
            if (entry.State == EntityState.Detached)
            {
                context.Set<T>().Attach(entity);
                entry.State = EntityState.Modified;
            }
            return entity;
        }
    }
}
